package com.atguigu.gulimall.auth.controller;

import com.atguigu.common.utils.R;
import com.atguigu.gulimall.auth.interceptor.CartInterceptor;
import com.atguigu.gulimall.auth.service.CartService;
import com.atguigu.gulimall.auth.to.UserInfoTO;
import com.atguigu.gulimall.auth.vo.Cart;
import com.atguigu.gulimall.auth.vo.CartItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.concurrent.ExecutionException;

@RestController
public class CartController {
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    CartService cartService;

    @GetMapping("/currentUserCartItems")
    public List<CartItem> getCurrentUserCartItems(){
        return cartService.getUserCartItems();
    }

    @GetMapping("/cart.html")
    public String cartList(HttpSession session,Model model) {
        //获取用户信息
//        UserInfoTO userInfoTO = CartInterceptor.threadLocal.get();
//        System.out.println(userInfoTO);
        Cart cart = cartService.getCart();
        model.addAttribute("cart",cart);

        return "cartList";
    }

    @GetMapping("/addToCart")
    public String addToCart(@RequestParam("skuId") Long skuId, @RequestParam("num") Integer num, RedirectAttributes redirectAttributes){
        cartService.addToCart(skuId,num);
        redirectAttributes.addAttribute("skuId", skuId);
        //做一个跳转，避免刷新导致重复添加
        return "redirect:/http://cart.gulimall.com/addToCartSuccess.html";
    }

    @GetMapping("/addToCartSuccess.html")
    public String addToCartSuccess(@RequestParam("skuId") Long skuId,Model model) {
        CartItem cartItem = cartService.getCartItem(skuId);
        model.addAttribute("item", cartItem);
        return "success";
    }

    @GetMapping("/checkItem.html")
    public R checkItem(@RequestParam("skuId") Long skuId, @RequestParam("check") Integer check) {
        cartService.checkItem(skuId,check);
        return R.ok();
    }

    @GetMapping("/countItem.html")
    public R countItem(@RequestParam("skuId") Long skuId, @RequestParam("num") Integer num) {
        cartService.changeItemCount(skuId,num);
        return R.ok();
    }

    @GetMapping("/deleteItem.html")
    public R deleteItem(@RequestParam("skuId") Long skuId) {
        cartService.deleteItem(skuId);
        return R.ok();
    }
}

